package com.kevin.netty.demo.packet.client;

import com.kevin.netty.demo.packet.handler.SimpleClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 用于测试编解码的客户端服务
 */
public class PacketEncodeNettyClient {

    public static void main(String[] args) {

        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                /**
                                 * 如果协议中的第一个字段为长度字段，netty提供了LengthFieldPrepender编码器，
                                 * 它可以计算当前待发送消息的二进制字节长度，将该长度添加到ByteBuf的缓冲区头中
                                 */
                                .addLast(new LengthFieldPrepender(4))
                                .addLast(new StringEncoder())
                                .addLast(new ChannelInboundHandlerAdapter(){
                                    @Override
                                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                        ctx.writeAndFlush("i am request!");
                                        ctx.writeAndFlush("i am a another request!");
                                    }
                                });
                    }
                });

        try {
            ChannelFuture channelFuture =  bootstrap.connect("localhost",8081).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            eventLoopGroup.shutdownGracefully();
        }

    }
}
